package com.aisb.core.shiro;

import com.aisb.core.SessionBean;
import com.aisb.login.LoginDao;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @Description：
 * @Author wucm
 * @Date 2018/1/7
 */

public class MyShiroRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    LoginDao loginDao;

    @Autowired
    ShiroDao shiroDao;

    /**
     * 权限验证
     *
     * @param collection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SessionBean u = (SessionBean) collection.getPrimaryPrincipal();
        String userId = u.getUserId();
        Boolean isAdmin = u.getAdmin();

        // 角色权限
        List<Map> roles = shiroDao.roleByUser(userId);
        for (Map role : roles) {
            info.addRole((String) role.get("roleId"));
        }

        // 功能权限和操作权限
        List<Map> funcs = shiroDao.funcAll();
        if (isAdmin) {// 超级管理员拥有所有权限
            for (Map func : funcs) {
                String funcUrl = (String) func.get("funcUrl");
                if (StringUtils.isBlank(funcUrl)) {
                    continue;
                }
                if (funcUrl.endsWith("/")) {
                    funcUrl = funcUrl.substring(0, funcUrl.length());
                }
                info.addStringPermission(funcUrl);
                if (funcUrl.endsWith("/index")) {// 获取功能授权关键KEY
                    funcUrl = funcUrl.replace("/index", "");
                }
                info.addStringPermission(funcUrl + "/add");
                info.addStringPermission(funcUrl + "/modify");
                info.addStringPermission(funcUrl + "/delete");
                info.addStringPermission(funcUrl + "/upload");
                info.addStringPermission(funcUrl + "/download");
            }
        } else { // 非超级管理员，分多种综合处理
            List<Map> funcByUserList = shiroDao.funcByUser(userId);
            List<Map> funcByRoleUserList = shiroDao.funcByRoleUser(userId);
            List<Map> operByUserList = shiroDao.operByUser(userId);
            List<Map> operByRoleUserList = shiroDao.operByRoleUser(userId);

            Set viewSet = new HashSet();
            Set addSet = new HashSet();
            Set modifySet = new HashSet();
            Set deleteSet = new HashSet();
            Set uploadSet = new HashSet();
            Set downloadSet = new HashSet();

            // 用户直接拥有的功能权限和操作权限
            for (Map m : funcByUserList) {
                String funcId = (String) m.get("funcId");
                String pAdd = (String) m.get("pAdd");
                String pModify = (String) m.get("pModify");
                String pDelete = (String) m.get("pDelete");
                String pUpload = (String) m.get("pUpload");
                String pDownload = (String) m.get("pDownload");

                viewSet.add(funcId);
                if ("true".equals(pAdd)) {
                    addSet.add(funcId);
                }
                if ("true".equals(pModify)) {
                    modifySet.add(funcId);
                }
                if ("true".equals(pDelete)) {
                    deleteSet.add(funcId);
                }
                if ("true".equals(pUpload)) {
                    uploadSet.add(funcId);
                }
                if ("true".equals(pDownload)) {
                    downloadSet.add(funcId);
                }
            }

            // 用户通过角色间接拥有的功能权限和操作权限
            for (Map m : funcByRoleUserList) {
                String funcId = (String) m.get("funcId");
                String pAdd = (String) m.get("pAdd");
                String pModify = (String) m.get("pModify");
                String pDelete = (String) m.get("pDelete");
                String pUpload = (String) m.get("pUpload");
                String pDownload = (String) m.get("pDownload");

                viewSet.add(funcId);
                if ("true".equals(pAdd)) {
                    addSet.add(funcId);
                }
                if ("true".equals(pModify)) {
                    modifySet.add(funcId);
                }
                if ("true".equals(pDelete)) {
                    deleteSet.add(funcId);
                }
                if ("true".equals(pUpload)) {
                    uploadSet.add(funcId);
                }
                if ("true".equals(pDownload)) {
                    downloadSet.add(funcId);
                }
            }

            boolean addFlag = false;
            boolean modifyFlag = false;
            boolean deleteFlag = false;
            boolean uploadFlag = false;
            boolean downloadFlag = false;

            // 用户直接拥有的操作权限
            for (Map m : operByUserList) {
                String pAdd = (String) m.get("pAdd");
                String pModify = (String) m.get("pModify");
                String pDelete = (String) m.get("pDelete");
                String pUpload = (String) m.get("pUpload");
                String pDownload = (String) m.get("pDownload");
                if ("true".equals(pAdd)) {
                    addFlag = true;
                }
                if ("true".equals(pModify)) {
                    modifyFlag = true;
                }
                if ("true".equals(pDelete)) {
                    deleteFlag = true;
                }
                if ("true".equals(pUpload)) {
                    uploadFlag = true;
                }
                if ("true".equals(pDownload)) {
                    downloadFlag = true;
                }
            }

            // 用户通过角色间接拥有的操作权限
            for (Map m : funcByRoleUserList) {
                String pAdd = (String) m.get("pAdd");
                String pModify = (String) m.get("pModify");
                String pDelete = (String) m.get("pDelete");
                String pUpload = (String) m.get("pUpload");
                String pDownload = (String) m.get("pDownload");
                if ("true".equals(pAdd)) {
                    addFlag = true;
                }
                if ("true".equals(pModify)) {
                    modifyFlag = true;
                }
                if ("true".equals(pDelete)) {
                    deleteFlag = true;
                }
                if ("true".equals(pUpload)) {
                    uploadFlag = true;
                }
                if ("true".equals(pDownload)) {
                    downloadFlag = true;
                }
            }

            for (Map func : funcs) {
                String funcId = (String) func.get("funcId");
                String funcUrl = (String) func.get("funcUrl");
                if (StringUtils.isBlank(funcUrl)) {
                    continue;
                }
                if (funcUrl.endsWith("/")) {
                    funcUrl = funcUrl.substring(0, funcUrl.length());
                }

                if (!viewSet.contains(funcId)) {
                    continue;
                }
                info.addStringPermission(funcUrl);
                if (funcUrl.endsWith("/index")) {// 获取功能授权关键KEY
                    funcUrl = funcUrl.replace("/index", "");
                }
                if (addSet.contains(funcId) || addFlag) {
                    info.addStringPermission(funcUrl + "/add");
                }
                if (modifySet.contains(funcId) || modifyFlag) {
                    info.addStringPermission(funcUrl + "/modify");
                }

                if (deleteSet.contains(funcId) || deleteFlag) {
                    info.addStringPermission(funcUrl + "/delete");
                }

                if (uploadSet.contains(funcId) || uploadFlag) {
                    info.addStringPermission(funcUrl + "/upload");
                }

                if (downloadSet.contains(funcId) || downloadFlag) {
                    info.addStringPermission(funcUrl + "/download");
                }
            }
        }

        logger.info("当前用户{}权限为{}", userId, JSONObject.toJSON(info).toString());

        return info;
    }


    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userId = (String) authenticationToken.getPrincipal();

        SessionBean sessionBean = (SessionBean) loginDao.queryOne(userId);
        if (null == sessionBean) {
            throw new AccountException("帐号不正确！");
        }

        sessionBean.setLogId(System.currentTimeMillis() + "");

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(sessionBean, sessionBean.getUserPwd(), getName());

        return simpleAuthenticationInfo;
    }
}
